package com.gujiangbo.future;


import java.util.concurrent.atomic.AtomicInteger;

public class FutureServiceImpl<IN, OUT> implements FutureService<IN, OUT> {

    private final static String FUTURE_THREAD_PREFIX = "FUTURE-";

    private final AtomicInteger nextCounter = new AtomicInteger(0);

    private String getNextName() {
        return FUTURE_THREAD_PREFIX + nextCounter.getAndIncrement();
    }


    @Override
    public Future<?> submit(Runnable runnable) {
        final FutureTask<Object> future = new FutureTask<>();
        new Thread(() -> {
            runnable.run();
            future.finish(null);
        }, getNextName()).start();

        return future;
    }

    @Override
    public Future submit(Task task, Object input) {
        FutureTask<Object> future = new FutureTask<>();
        new Thread(() -> {
            Object o = task.get(input);
            future.finish(o);
        }, getNextName()).start();

        return future;
    }
}
